#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/select.h>
#include "config.h"
#include "build_link.h"
#include "radar_protocol.h"
#include "platform_protocol.h"
#include "platform.h"
#include "log.h"

extern server_config_t g_server_config;

static void send_to_platform(char *buffer, size_t len)
{
    if (g_server_config.platform_client_sock == -1) {
        return;
    }
    if (len > PLATFORM_PROTOCOL_DATA_SIZE) {
        return;
    }
    // 发送数据到平台
    send(g_server_config.platform_client_sock, buffer, len, 0);
}

void send_statistics_data(radar_packet_80_t *radar_data, uint8_t dev_type)
{
    char buffer[PLATFORM_PROTOCOL_DATA_SIZE] = {0};
    size_t data_len = pack_platform_static_data(buffer, radar_data, dev_type);
    if (data_len > 0) {
        // print_hex_buffer((const char *)buffer, data_len);
        // write_hex_log("平台协议", " ", buffer, data_len);
        send_to_platform(buffer, data_len);
    }
}

void send_event_to_platform(radar_packet_84_t *radar_data, uint8_t *time_stamp, uint8_t dev_type)
{
    char buffer[PLATFORM_PROTOCOL_DATA_SIZE] = {0};
    size_t data_len = pack_platform_event_data(buffer, radar_data, time_stamp, dev_type);
    if (data_len > 0) {
        // print_hex_buffer((const char *)buffer, data_len);
        // write_hex_log("平台协议", " ", buffer, data_len);
        send_to_platform(buffer, data_len);
    }
}

void send_realtime_data(platform_protocol_mix_data_t *mix_data, size_t mix_num, uint8_t dev_type)
{
    char buffer[PLATFORM_PROTOCOL_DATA_SIZE] = {0};
    size_t data_len = pack_platform_realtime_data(buffer, mix_data, mix_num, dev_type);
    if (data_len > 0) {
        // print_hex_buffer((unsigned char *)buffer, data_len);
        // write_hex_log("平台协议", dev_type == RADAR_INCOMING ? "来向雷达" : "去向雷达", buffer, data_len);
        send_to_platform(buffer, data_len);
    }
}

void send_pole_relay_data(platform_protocol_pole_relay_data_t *relay_data, size_t mix_num)
{
    char buffer[PLATFORM_PROTOCOL_DATA_SIZE] = {0};
    size_t data_len = pack_platform_relay_data(buffer, relay_data, mix_num);
    if (data_len > 0) {
        // printf("发送杆杆接力数据\n");
        // print_hex_buffer((unsigned char *)buffer, data_len);
        // write_hex_log("平台协议", " ", buffer, data_len);
        send_to_platform(buffer, data_len);
    }
}
